package com.jyszkj.map.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.text.style.TtsSpan.TimeBuilder
import android.util.AttributeSet
import android.util.Log
import com.jyszkj.map.bean.DeviceBean
import com.jyszkj.map.constant.MapConstants
import com.jyszkj.map.listener.MapChangeListener
import com.jyszkj.map.listener.MapClickListener
import com.jyszkj.map.util.CircleZoomCalculator
import com.jyszkj.map.util.MapManager
import com.jyszkj.osmdroid.map.R
import org.osmdroid.events.MapListener
import org.osmdroid.events.ScrollEvent
import org.osmdroid.events.ZoomEvent
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Overlay




class OsmdroidMapView(private var context: Context, attrs: AttributeSet) : MapView(context, attrs) {
    private var mType = 0
    private var mTheme = 0
    private var mTerminalType = 0
    private var zoom = 5
    private var mCornerRadius = 0f
    private lateinit var mapManager: MapManager
    private val clipPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG) // 启用抗锯齿

    init {
        try {
            val a = context.obtainStyledAttributes(attrs, R.styleable.OsmdroidMapView)
            mType = a.getInt(R.styleable.OsmdroidMapView_map_type, 0)
            mTheme = a.getInt(R.styleable.OsmdroidMapView_map_theme, 0)
            mTerminalType = a.getInt(R.styleable.OsmdroidMapView_map_terminal_type,0)
            zoom = a.getInt(R.styleable.OsmdroidMapView_map_zoom,5)
            mCornerRadius = a.getDimension(R.styleable.OsmdroidMapView_map_cornerRadius,0f)
            a.recycle()
        } catch (e: Exception){
            e.printStackTrace()
        }
        init()
    }

    private fun init() {
        mapManager = MapManager(context, this, mTerminalType)
        setType(mType)
        setTheme(mTheme)
        setZoom(zoom.toDouble())
        invalidate()
    }

    /**
     * 设置地图类型
     */
    fun setType(type: Int) {
        when(type) {
            MapConstants.MAP_TYPE_TERRAIN -> {
                mapManager.switchMapType(MapManager.MapType.TERRAIN)
            }
            MapConstants.MAP_TYPE_OFFLINE_TERRAIN -> {
                mapManager.switchMapType(MapManager.MapType.OFFLINE_TERRAIN)
            }
            else -> {
                mapManager.switchMapType(MapManager.MapType.STANDARD)
            }
        }
        invalidate()
    }

    /**
     * 设置地图主题
     */
    private fun setTheme(theme: Int) {
        when(theme) {
            MapConstants.MAP_THEME_BLUE -> {
                mapManager.switchMapTheme(MapManager.MapTheme.BLUE)
            }
            MapConstants.MAP_THEME_GREEN -> {
                mapManager.switchMapTheme(MapManager.MapTheme.GREEN)
            }
            MapConstants.MAP_THEME_LIGHT_GREEN -> {
                mapManager.switchMapTheme(MapManager.MapTheme.LIGHT_GREEN)
            }
        }
    }

    /**
     * 设置偏移
     */
    fun setMapOffset(offsetX: Int, offsetY: Int) {
        setMapCenterOffset(offsetX,offsetY)
    }

    /**
     * 设置是否可滑动
     */
    fun setMapScrollable(enabled: Boolean) {
        mapManager.setMapScrollable(enabled)
    }

    /**
     * 显示预警位置
     */
    fun showWarnLocation(lon: Double, lat: Double, level: Int, address: String?) {
        mapManager.setCenter(lon, lat)
        val marker = mapManager.getWarnMarker(GeoPoint(lat, lon),level,address)
        clearMarker()
        this.overlays.add(marker)
        invalidate()
        if(!address.isNullOrEmpty()) {
            postDelayed({ marker.showInfoWindow() }, 500)
        }
    }

    fun setCenter(lon: Double, lat: Double) {
        mapManager.setCenter(lon, lat)
    }

    /**
     * 显示预警标记,两个标记之间平滑切换
     */
    fun showWarnMarker(lon: Double, lat: Double, level: Int, address: String, speed: Long) {
        val geoPoint = GeoPoint(lat, lon)
        val marker = mapManager.getWarnMarker(geoPoint,level,address)
        animateTo(marker, geoPoint, speed, true)
    }

    private fun animateTo(maker: Marker, point: GeoPoint, speed: Long, isClear: Boolean = false) {
        controller.animateTo(point, 5.0, speed)
        if(isClear) {
            clearMarker()
        }
        overlays.add(maker)
        maker.showInfoWindow()
    }

    fun animateTo(lon: Double, lat: Double, speed: Long) {
        controller.animateTo(GeoPoint(lat, lon), zoomLevelDouble, speed)
    }

    fun animateTo(lon: Double, lat: Double, zoom: Double,speed: Long) {
        controller.animateTo(GeoPoint(lat, lon), zoom, speed)
    }



    /**
     * 显示当前位置标记，根据距离进行缩放和放大
     * @param lon 经度
     * @param lat 纬度
     * @param distance 距离
     */
    fun showCurrentMaker(lon: Double, lat: Double, distance: Double, paddingHeight: Int = 0){
        mapManager.setCenter(lon, lat)
        val geoPoint = GeoPoint(lat, lon)
        val marker = mapManager.getCurrentLocationMarker(geoPoint)
        this.overlays.add(marker)
        if(distance > -1) {
            post {
                CircleZoomCalculator.setPerfectZoomForCircle(
                    this,
                    GeoPoint(lat, lon),
                    distance * 1000,
                    paddingHeight
                )
            }
        }
        invalidate()
        postDelayed({ marker.showInfoWindow() }, if(distance > -1) 500 else 0)
    }

    /**
     * 显示当前位置标记，根据距离进行缩放和放大
     * @param lon 经度
     * @param lat 纬度
     * @param distance 距离
     */
    fun showCurrentMakerYqy(lon: Double, lat: Double, distance: Double, paddingHeight: Int){
        mapManager.setCenter(lon, lat)
        val geoPoint = GeoPoint(lat, lon)
        val marker = mapManager.getCurrentLocationMarkerYqy(geoPoint)
        this.overlays.add(marker)
        if(distance > -1) {
            post {
                CircleZoomCalculator.setPerfectZoomForCircle(
                    this,
                    GeoPoint(lat, lon),
                    distance * 1000,
                    paddingHeight
                )
            }
        }
        invalidate()
        postDelayed({ marker.showInfoWindow() }, if(distance > -1) 500 else 0)
    }

    fun autoZoom(centerLon: Double, centerLat: Double, distance: Double, offsetZoom: Int) {
        post {
            CircleZoomCalculator.setPerfectDeviceZoomForCircle(this,GeoPoint(centerLat,centerLon),distance * 1000, offsetZoom = offsetZoom)
        }
        invalidate()
    }

    /**
     * 显示避难所
     */
    fun showShelterMarker(lon: Double, lat: Double, value: String, address: String = "") {
        val marker = mapManager.getShelterMaker(lon,lat,value,address)
        this.overlays.add(marker)
        invalidate()
    }

    /**
     * 显示避难所
     */
    fun showShelterMarkerYqy(lon: Double, lat: Double, value: String, address: String = "") {
        val marker = mapManager.getShelterMakerYqy(lon,lat,value,address)
        this.overlays.add(marker)
        invalidate()
    }

    fun showDeviceMarker(bean: DeviceBean) {
        val maker = mapManager.getDeviceMarker(bean)
        this.overlays.add(maker)
    }

    fun showDeviceListMarker(list: List<DeviceBean>){
        clearMarker()
        list.forEach {
            showDeviceMarker(it)
        }
        invalidate()
    }

    fun closeInfoWindow() {
        // 遍历并关闭所有 Marker 的 InfoWindow
        for (overlay in overlays) {
            if (overlay is Marker) {
                if (overlay.isInfoWindowShown) {
                    overlay.closeInfoWindow() // 关闭 InfoWindow
                }
            }
        }
    }


    /**
     * 清除所有标记
     */
    fun clearMarker() {
        mapManager.clearMarker()
    }

    /**
     * 设置地图点击监听
     */
    fun setMapClickListener(mapClickListener: MapClickListener) {
        mapManager.setMapClickListener(mapClickListener)
    }

    /**
     * 设置缩放
     */
    fun setZoom(zoom: Double) {
        mapManager.setZoom(zoom)
    }

    fun zoomIn() {
        mapManager.zoomIn()
    }

    fun zoomOut() {
        mapManager.zoomOut()
    }

    fun setOnMapChangedListener(listener: MapChangeListener) {
        postDelayed({
            addMapListener(object : MapListener {
                override fun onScroll(event: ScrollEvent?): Boolean {
                    listener.onMapChanged()
                    return false
                }

                override fun onZoom(event: ZoomEvent?): Boolean {
                    listener.onMapChanged()
                    return false
                }
            })
        },1000)
    }

    override fun dispatchDraw(canvas: Canvas) {
        val path = Path().apply {
            addRoundRect(
                0f, 0f, width.toFloat(), height.toFloat(),
                mCornerRadius, mCornerRadius, Path.Direction.CW
            )
        }
        canvas.clipPath(path)
        super.dispatchDraw(canvas)
    }

}